'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
	try {
		console.log('Cloud function [getBidInfoForSupplier] started.');

		if (!event) {
			console.error('Event object is null or undefined.');
			return { errCode: 'INVALID_PARAM', errMsg: 'Event object is missing.' };
		}
		console.log('Event object:', JSON.stringify(event));

		if (!context) {
			console.error('Context object is null or undefined.');
			return { errCode: 'INVALID_CONTEXT', errMsg: 'Context object is missing.' };
		}
		
		const { auctionId } = event;
		const auth = context.auth;

		console.log('Auth object exists:', !!auth);

		if (!auth) {
			console.log('Auth object is null or undefined. User not logged in.');
			return {
				errCode: 'NOT_LOGIN',
				errMsg: '用户未登录或登录已过期'
			};
		}

		const { uid } = auth;
		console.log('Current user UID:', uid);
		console.log('Querying for auction ID:', auctionId);

		const bidsRes = await db.collection('bids')
			.where({
				auction_id: auctionId
			})
			.orderBy('amount', 'asc')
			.orderBy('timestamp', 'asc')
			.get();

		console.log('Bids query result:', JSON.stringify(bidsRes));
		
		const bids = bidsRes.data;

		if (!bids || bids.length === 0) {
			console.log('No bids found for this auction.');
			return { errCode: 0, data: { myBid: null, myRank: 0 } };
		}

		const myBidIndex = bids.findIndex(bid => bid.supplier_user_id === uid);
		console.log('Found my bid index:', myBidIndex);

		if (myBidIndex === -1) {
			console.log('Current user bid not found in the list.');
			return { errCode: 0, data: { myBid: null, myRank: 0 } };
		}

		console.log('Successfully found bid info.');
		return {
			errCode: 0,
			data: {
				myBid: bids[myBidIndex],
				myRank: myBidIndex + 1
			}
		};
	} catch (e) {
		console.error('CRITICAL_ERROR in getBidInfoForSupplier:', e.message);
		console.error('Error stack:', e.stack);
		return {
			errCode: 'FUNCTION_CRASH',
			errMsg: '云函数执行出现严重错误: ' + e.message
		}
	}
};